<template>
  <PageLayout
    title="用户组管理"
    subtitle="管理系统用户组"
    icon="fa fa-users"
    class="apply-glass-theme"
  >
    <template #toolbar-left>
      <el-button type="primary" @click="showCreateDialog" class="tech-button">
        <i class="fa fa-plus"></i> 新增用户组
      </el-button>
      <el-button @click="refreshGroups" class="tech-button">
        <i class="fa fa-refresh"></i> 刷新
      </el-button>
    </template>

    <template #toolbar-right>
      <el-input
        v-model="searchText"
        placeholder="搜索用户组名称或描述..."
        clearable
        class="tech-input"
        style="width: 350px"
      >
        <template #prefix>
          <i class="fa fa-search"></i>
        </template>
      </el-input>
    </template>

    <template #content>
      <div class="glass-card">
        <el-table
          :data="filteredGroups"
          v-loading="loading"
          class="glass-dialog tech-table"
          stripe
          border
          height="calc(100vh - 380px)"
          style="width: 100%;"
          table-layout="fixed"
        >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="组名" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="成员数量" width="120">
          <template #default="{ row }">
            <el-tag type="info">{{ row.user_count || 0 }} 人</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="关联角色" width="200">
          <template #default="{ row }">
            <div v-if="row.roles && row.roles.length > 0" class="role-tags">
              <el-tag
                v-for="role in row.roles"
                :key="role.id"
                :type="role.is_system ? 'warning' : 'success'"
                size="small"
                style="margin-right: 5px; margin-bottom: 2px;"
              >
                {{ role.name }}
              </el-tag>
            </div>
            <span v-else class="text-muted">未分配角色</span>
          </template>
        </el-table-column>
        <el-table-column label="角色数量" width="120">
          <template #default="{ row }">
            <el-tag type="success">{{ row.role_count || 0 }} 个</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="380" fixed="right" align="center">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                size="small"
                type="primary"
                @click="editGroup(row)"
                class="action-btn glass-button"
              >
                <i class="fa fa-edit"></i> 编辑
              </el-button>
              <el-button
                size="small"
                type="info"
                @click="manageMembers(row)"
                class="action-btn glass-button"
              >
                <i class="fa fa-users"></i> 成员
              </el-button>
              <el-button
                size="small"
                type="warning"
                @click="manageRoles(row)"
                class="action-btn glass-button"
              >
                <i class="fa fa-user-tag"></i> 角色
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="deleteGroup(row)"
                class="action-btn glass-button"
              >
                <i class="fa fa-trash"></i> 删除
              </el-button>
            </div>
          </template>
        </el-table-column>
        </el-table>
      </div>
    </template>

    <template #dialogs>
      <!-- 创建/编辑用户组对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="650px"
        class="tech-dialog"
      >
        <el-form :model="groupForm" :rules="groupRules" ref="groupFormRef" label-width="100px" class="tech-form">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="组名" prop="name">
                <el-input v-model="groupForm.name" placeholder="请输入用户组名称" class="tech-input" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="描述" prop="description">
                <el-input v-model="groupForm.description" type="textarea" :rows="3" placeholder="请输入用户组描述" class="tech-input" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false" class="tech-button">取消</el-button>
            <el-button type="primary" @click="saveGroup" class="tech-button">
              {{ isEdit ? '更新' : '创建' }}
            </el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 管理成员对话框 -->
      <el-dialog
        v-model="membersDialogVisible"
        title="管理组成员"
        width="800px"
        class="tech-dialog"
      >
        <div class="members-management">
          <div class="members-section">
            <h4>当前成员</h4>
            <el-table :data="currentMembers" class="glass-dialog tech-table" stripe border>
              <el-table-column prop="username" label="用户名" />
              <el-table-column prop="email" label="邮箱" />
              <el-table-column prop="first_name" label="姓名" />
              <el-table-column label="操作" width="100">
                <template #default="{ row }">
                  <el-button size="small" type="danger" @click="removeMember(row)" class="tech-button">
                    <i class="fa fa-minus"></i> 移除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="add-members-section">
            <h4>添加成员</h4>
            <el-select
              v-model="selectedUsers"
              multiple
              placeholder="选择要添加的用户"
              style="width: 100%"
              filterable
              class="tech-input"
            >
              <el-option
                v-for="user in availableUsers"
                :key="user.id"
                :label="`${user.username} (${user.email})`"
                :value="user.id"
              />
            </el-select>
            <div style="margin-top: 10px;">
              <el-button type="primary" @click="addMembers" class="tech-button">
                <i class="fa fa-plus"></i> 添加选中用户
              </el-button>
            </div>
          </div>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="membersDialogVisible = false" class="tech-button">关闭</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 管理角色对话框 -->
      <el-dialog
        v-model="rolesDialogVisible"
        title="管理组角色"
        width="800px"
        class="tech-dialog"
      >
        <div class="roles-management">
          <div class="current-roles-section">
            <h4>当前角色</h4>
            <div v-if="currentGroupRoles.length > 0" class="role-list">
              <el-tag
                v-for="role in currentGroupRoles"
                :key="role.id"
                :type="role.is_system ? 'warning' : 'success'"
                closable
                @close="removeRole(role)"
                style="margin-right: 8px; margin-bottom: 8px;"
              >
                {{ role.name }}
                <span v-if="role.is_system" style="margin-left: 5px;">(系统)</span>
              </el-tag>
            </div>
            <div v-else class="no-roles">
              <el-empty description="该用户组暂未分配任何角色" :image-size="80" />
            </div>
          </div>

          <div class="assign-roles-section">
            <h4>分配角色</h4>
            <el-select
              v-model="selectedRoles"
              multiple
              placeholder="选择要分配的角色"
              style="width: 100%"
              filterable
              class="tech-input"
            >
              <el-option
                v-for="role in availableRoles"
                :key="role.id"
                :label="role.name"
                :value="role.id"
              >
                <span>{{ role.name }}</span>
                <span v-if="role.is_system" style="color: #f56c6c; margin-left: 10px;">(系统角色)</span>
                <span v-else style="color: #67c23a; margin-left: 10px;">(自定义角色)</span>
              </el-option>
            </el-select>
            <div style="margin-top: 10px;">
              <el-button type="primary" @click="assignRoles" class="tech-button">
                <i class="fa fa-plus"></i> 分配选中角色
              </el-button>
            </div>
          </div>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="rolesDialogVisible = false" class="tech-button">关闭</el-button>
          </div>
        </template>
      </el-dialog>
    </template>
  </PageLayout>
</template>

<script setup lang="ts">
import PageLayout from '@/components/PageLayout.vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, onMounted, ref } from 'vue'

// 响应式数据
const loading = ref(false)
const groups = ref([])
const users = ref([])
const roles = ref([])
const searchText = ref('')
const dialogVisible = ref(false)
const membersDialogVisible = ref(false)
const rolesDialogVisible = ref(false)
const isEdit = ref(false)
const groupFormRef = ref()
const currentGroup = ref(null)
const currentMembers = ref([])
const currentGroupRoles = ref([])
const selectedUsers = ref([])
const selectedRoles = ref([])

// 用户组表单
const groupForm = ref({
  id: null,
  name: '',
  description: ''
})

// 表单验证规则
const groupRules = {
  name: [
    { required: true, message: '请输入组名', trigger: 'blur' },
    { min: 2, max: 50, message: '组名长度在 2 到 50 个字符', trigger: 'blur' }
  ]
}

// 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑用户组' : '新增用户组')
const filteredGroups = computed(() => {
  if (!searchText.value) return groups.value
  return groups.value.filter((group: any) =>
    group.name.toLowerCase().includes(searchText.value.toLowerCase()) ||
    (group.description && group.description.toLowerCase().includes(searchText.value.toLowerCase()))
  )
})

const availableUsers = computed(() => {
  const currentMemberIds = currentMembers.value.map((member: any) => member.id)
  return users.value.filter((user: any) => !currentMemberIds.includes(user.id))
})

const availableRoles = computed(() => {
  const currentRoleIds = currentGroupRoles.value.map((role: any) => role.id)
  return roles.value.filter((role: any) => !currentRoleIds.includes(role.id))
})

// 方法
const fetchGroups = async () => {
  loading.value = true
  try {
    const response = await axios.get('/api/groups/')
    groups.value = response.data.results || response.data
  } catch (error) {
    console.error('获取用户组列表失败:', error)
    ElMessage.error('获取用户组列表失败')
  } finally {
    loading.value = false
  }
}

const fetchUsers = async () => {
  try {
    const response = await axios.get('/api/users/')
    users.value = response.data.results || response.data
  } catch (error) {
    console.error('获取用户列表失败:', error)
  }
}

const fetchRoles = async () => {
  try {
    const response = await axios.get('/api/roles/')
    roles.value = response.data.results || response.data
  } catch (error) {
    console.error('获取角色列表失败:', error)
  }
}

const refreshGroups = () => {
  fetchGroups()
}

const showCreateDialog = () => {
  isEdit.value = false
  groupForm.value = {
    id: null,
    name: '',
    description: ''
  }
  dialogVisible.value = true
}

const editGroup = (group: any) => {
  isEdit.value = true
  groupForm.value = {
    id: group.id,
    name: group.name,
    description: group.description || ''
  }
  dialogVisible.value = true
}

const saveGroup = async () => {
  try {
    await groupFormRef.value.validate()

    if (isEdit.value) {
      await axios.put(`/api/groups/${groupForm.value.id}/`, groupForm.value)
      ElMessage.success('用户组更新成功')
    } else {
      await axios.post('/api/groups/', groupForm.value)
      ElMessage.success('用户组创建成功')
    }

    dialogVisible.value = false
    fetchGroups()
  } catch (error) {
    console.error('保存用户组失败:', error)
    ElMessage.error('保存用户组失败')
  }
}

const deleteGroup = async (group: any) => {
  try {
    await ElMessageBox.confirm('确定要删除这个用户组吗？', '确认删除', {
      type: 'warning'
    })

    await axios.delete(`/api/groups/${group.id}/`)
    ElMessage.success('用户组删除成功')
    fetchGroups()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户组失败:', error)
      ElMessage.error('删除用户组失败')
    }
  }
}

const manageMembers = async (group: any) => {
  currentGroup.value = group
  try {
    const response = await axios.get(`/api/groups/${group.id}/members/`)
    currentMembers.value = response.data
    selectedUsers.value = []
    membersDialogVisible.value = true
  } catch (error) {
    console.error('获取组成员失败:', error)
    ElMessage.error('获取组成员失败')
  }
}

const addMembers = async () => {
  if (selectedUsers.value.length === 0) {
    ElMessage.warning('请选择要添加的用户')
    return
  }

  try {
    await axios.post(`/api/groups/${currentGroup.value.id}/add_members/`, {
      user_ids: selectedUsers.value
    })
    ElMessage.success('成员添加成功')
    manageMembers(currentGroup.value) // 刷新成员列表
  } catch (error) {
    console.error('添加成员失败:', error)
    ElMessage.error('添加成员失败')
  }
}

const removeMember = async (user: any) => {
  try {
    await ElMessageBox.confirm(`确定要将 ${user.username} 从组中移除吗？`, '确认移除', {
      type: 'warning'
    })

    await axios.post(`/api/groups/${currentGroup.value.id}/remove_members/`, {
      user_ids: [user.id]
    })
    ElMessage.success('成员移除成功')
    manageMembers(currentGroup.value) // 刷新成员列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('移除成员失败:', error)
      ElMessage.error('移除成员失败')
    }
  }
}

const manageRoles = async (group: any) => {
  currentGroup.value = group
  try {
    const response = await axios.get(`/api/groups/${group.id}/roles/`)
    console.log('获取到的组角色数据:', response.data)

    // 从GroupRole对象中提取角色信息，需要根据role ID获取完整的角色对象
    const roleIds = response.data.map((gr: any) => gr.role)
    console.log('角色ID列表:', roleIds)

    // 从已加载的角色列表中找到对应的角色对象
    currentGroupRoles.value = roles.value.filter((role: any) => roleIds.includes(role.id))
    console.log('当前组角色:', currentGroupRoles.value)

    selectedRoles.value = []
    rolesDialogVisible.value = true
  } catch (error) {
    console.error('获取组角色失败:', error)
    ElMessage.error('获取组角色失败')
  }
}

const assignRoles = async () => {
  if (selectedRoles.value.length === 0) {
    ElMessage.warning('请选择要分配的角色')
    return
  }

  try {
    console.log('当前角色ID:', currentGroupRoles.value.map((role: any) => role.id))
    console.log('选择的新角色ID:', selectedRoles.value)

    // 合并当前角色和新选择的角色
    const currentRoleIds = currentGroupRoles.value.map((role: any) => role.id)
    const allRoleIds = [...currentRoleIds, ...selectedRoles.value]

    console.log('合并后的角色ID:', allRoleIds)

    await axios.post(`/api/groups/${currentGroup.value.id}/assign_roles/`, {
      role_ids: allRoleIds
    })
    ElMessage.success('角色分配成功')

    // 清空选择的角色
    selectedRoles.value = []

    // 刷新角色列表和用户组列表
    await manageRoles(currentGroup.value)
    await fetchGroups()
  } catch (error) {
    console.error('分配角色失败:', error)
    ElMessage.error('分配角色失败')
  }
}

const removeRole = async (role: any) => {
  try {
    await ElMessageBox.confirm(`确定要移除角色 ${role.name} 吗？`, '确认移除', {
      type: 'warning'
    })

    // 获取剩余的角色ID
    const remainingRoleIds = currentGroupRoles.value
      .filter((r: any) => r.id !== role.id)
      .map((r: any) => r.id)

    // 使用assign_roles API重新分配剩余角色（如果为空数组则清除所有角色）
    await axios.post(`/api/groups/${currentGroup.value.id}/assign_roles/`, {
      role_ids: remainingRoleIds
    })

    ElMessage.success('角色移除成功')

    // 刷新角色列表和用户组列表
    await manageRoles(currentGroup.value)
    await fetchGroups()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('移除角色失败:', error)
      // 显示更详细的错误信息
      if (error.response && error.response.data && error.response.data.error) {
        ElMessage.error(`移除角色失败: ${error.response.data.error}`)
      } else {
        ElMessage.error('移除角色失败')
      }
    }
  }
}

// 生命周期
onMounted(() => {
  fetchGroups()
  fetchUsers()
  fetchRoles()
})
</script>

<style scoped>
/* 透明玻璃按钮样式 */
:deep(.el-button) {
  background: rgba(255, 255, 255, 0.05) !important;
  border: 1px solid rgba(255, 255, 255, 0.1) !important;
  color: rgba(255, 255, 255, 0.9) !important;
  backdrop-filter: blur(10px) !important;
  transition: all 0.3s ease !important;
  border-radius: 8px !important;
  font-weight: 500 !important;

  &:hover {
    background: rgba(255, 255, 255, 0.1) !important;
    border-color: rgba(0, 234, 255, 0.3) !important;
    transform: translateY(-1px) !important;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2) !important;
    color: #ffffff !important;
  }

  &.el-button--primary {
    background: linear-gradient(135deg, rgba(0, 234, 255, 0.8), rgba(0, 153, 204, 0.8)) !important;
    border-color: rgba(0, 234, 255, 0.6) !important;
    color: #ffffff !important;
    box-shadow: 0 4px 15px rgba(0, 234, 255, 0.3) !important;

    &:hover {
      background: linear-gradient(135deg, rgba(51, 240, 255, 0.9), rgba(0, 184, 230, 0.9)) !important;
      box-shadow: 0 6px 20px rgba(0, 234, 255, 0.4) !important;
    }
  }

  &.el-button--info {
    background: linear-gradient(135deg, rgba(108, 117, 125, 0.8), rgba(73, 80, 87, 0.8)) !important;
    border-color: rgba(108, 117, 125, 0.6) !important;
    color: #ffffff !important;
    box-shadow: 0 4px 15px rgba(108, 117, 125, 0.3) !important;

    &:hover {
      background: linear-gradient(135deg, rgba(130, 138, 145, 0.9), rgba(90, 98, 104, 0.9)) !important;
      box-shadow: 0 6px 20px rgba(108, 117, 125, 0.4) !important;
    }
  }

  &.el-button--warning {
    background: linear-gradient(135deg, rgba(255, 193, 7, 0.8), rgba(255, 152, 0, 0.8)) !important;
    border-color: rgba(255, 193, 7, 0.6) !important;
    color: #ffffff !important;
    box-shadow: 0 4px 15px rgba(255, 193, 7, 0.3) !important;

    &:hover {
      background: linear-gradient(135deg, rgba(255, 206, 84, 0.9), rgba(255, 167, 38, 0.9)) !important;
      box-shadow: 0 6px 20px rgba(255, 193, 7, 0.4) !important;
    }
  }

  &.el-button--danger {
    background: linear-gradient(135deg, rgba(220, 53, 69, 0.8), rgba(176, 42, 55, 0.8)) !important;
    border-color: rgba(220, 53, 69, 0.6) !important;
    color: #ffffff !important;
    box-shadow: 0 4px 15px rgba(220, 53, 69, 0.3) !important;

    &:hover {
      background: linear-gradient(135deg, rgba(225, 83, 97, 0.9), rgba(190, 60, 75, 0.9)) !important;
      box-shadow: 0 6px 20px rgba(220, 53, 69, 0.4) !important;
    }
  }

  &:disabled {
    background: rgba(255, 255, 255, 0.02) !important;
    border-color: rgba(255, 255, 255, 0.05) !important;
    color: rgba(255, 255, 255, 0.3) !important;
    cursor: not-allowed !important;
    transform: none !important;
    box-shadow: none !important;
  }
}

/* 操作按钮容器样式优化 */
.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: nowrap;
  justify-content: center;
  align-items: center;
  min-width: 340px;
  padding: 4px;
}

.action-btn {
  min-width: 70px !important;
  height: 34px !important;
  padding: 0 10px !important;
  border-radius: 8px !important;
  font-size: 12px !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  transition: all 0.3s ease !important;
  white-space: nowrap !important;
  flex-shrink: 0 !important;

  i {
    font-size: 12px !important;
    margin-right: 4px !important;
  }
}

/* 确保表格操作列有足够的空间且不被遮挡 */
:deep(.el-table .el-table__cell) {
  padding: 8px 4px !important;
  position: relative !important;
}

:deep(.el-table .el-table__cell:has(.action-buttons)) {
  padding: 8px 12px !important;
  overflow: visible !important;
  z-index: 10 !important;
  position: relative !important;
}

/* 优化表格行高 */
:deep(.el-table .el-table__row) {
  height: 50px !important;
  position: relative !important;
}

/* 确保固定列不遮挡按钮 */
:deep(.el-table__fixed-right) {
  z-index: 5 !important;
}

:deep(.el-table__fixed-right .el-table__cell) {
  z-index: 10 !important;
  background: rgba(13, 21, 43, 0.95) !important;
  backdrop-filter: blur(10px) !important;
}

/* 确保按钮在小屏幕上也能正常显示 */
@media (max-width: 1200px) {
  .action-buttons {
    flex-wrap: wrap;
    gap: 4px;
    min-width: 320px;
  }

  .action-btn {
    min-width: 65px !important;
    font-size: 11px !important;
    padding: 0 8px !important;
  }
}

.members-management,
.roles-management {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.members-section h4,
.add-members-section h4,
.current-roles-section h4,
.assign-roles-section h4 {
  margin: 0 0 10px 0;
  color: #00eaff;
}

.role-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.role-list {
  min-height: 60px;
  padding: 10px;
  border: 1px dashed rgba(0, 234, 255, 0.3);
  border-radius: 4px;
  background: rgba(0, 234, 255, 0.05);
}

.no-roles {
  text-align: center;
  padding: 20px;
}

.text-muted {
  color: rgba(255, 255, 255, 0.6);
  font-style: italic;
}

/* 透明玻璃弹窗样式 */
:deep(.el-dialog) {
  background: rgba(255, 255, 255, 0.02) !important;
  border: 1px solid rgba(255, 255, 255, 0.08) !important;
  backdrop-filter: blur(20px) saturate(150%) !important;
  border-radius: 16px !important;
  box-shadow:
    0 8px 32px rgba(0, 0, 0, 0.3),
    inset 0 1px 0 rgba(255, 255, 255, 0.1) !important;

  .el-dialog__header {
    background: transparent !important;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1) !important;
    padding: 20px 24px 16px 24px !important;

    .el-dialog__title {
      color: #ffffff !important;
      font-size: 18px !important;
      font-weight: 600 !important;
      text-shadow: 0 0 10px rgba(255, 255, 255, 0.3) !important;
    }

    .el-dialog__headerbtn {
      .el-dialog__close {
        color: rgba(255, 255, 255, 0.7) !important;
        font-size: 18px !important;

        &:hover {
          color: #ff4757 !important;
        }
      }
    }
  }

  .el-dialog__body {
    background: transparent !important;
    padding: 24px !important;
    color: #ffffff !important;
  }

  .el-dialog__footer {
    background: transparent !important;
    border-top: 1px solid rgba(255, 255, 255, 0.1) !important;
    padding: 16px 24px 20px 24px !important;
  }
}

/* 表单样式优化 */
:deep(.el-form-item__label) {
  color: rgba(255, 255, 255, 0.9) !important;
  font-weight: 500 !important;
}

:deep(.el-input) {
  .el-input__wrapper {
    background: rgba(255, 255, 255, 0.05) !important;
    border: 1px solid rgba(255, 255, 255, 0.1) !important;
    backdrop-filter: blur(10px) !important;
    border-radius: 8px !important;

    &:hover {
      border-color: rgba(0, 234, 255, 0.3) !important;
    }

    &.is-focus {
      border-color: rgba(0, 234, 255, 0.6) !important;
      box-shadow: 0 0 0 2px rgba(0, 234, 255, 0.2) !important;
    }

    .el-input__inner {
      color: #ffffff !important;
      background: transparent !important;

      &::placeholder {
        color: rgba(255, 255, 255, 0.5) !important;
      }
    }
  }
}

:deep(.el-select) {
  .el-select__wrapper {
    background: rgba(255, 255, 255, 0.05) !important;
    border: 1px solid rgba(255, 255, 255, 0.1) !important;
    backdrop-filter: blur(10px) !important;
    border-radius: 8px !important;

    &:hover {
      border-color: rgba(0, 234, 255, 0.3) !important;
    }

    &.is-focused {
      border-color: rgba(0, 234, 255, 0.6) !important;
      box-shadow: 0 0 0 2px rgba(0, 234, 255, 0.2) !important;
    }

    .el-select__selected-item {
      color: #ffffff !important;
    }

    .el-select__placeholder {
      color: rgba(255, 255, 255, 0.5) !important;
    }
  }
}
</style>
